package com.junglone.gateway.admin.filter;

import java.net.URI;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;

import reactor.core.publisher.Mono;

/**
 * Description: 登录过滤
 *
 * @author junglone: <a href="mailto:cjlnzb@hotmail.com">cjlnzb@hotmail.com</a>
 * @since 2021/03/31 14:40
 */

@Order(66)
@Component
public class LoginFilter implements WebFilter {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoginFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {

        ServerHttpRequest serverRequest = exchange.getRequest();

        String strCurrentPath = serverRequest.getPath().value();
        LOGGER.info("strCurrentPath ---- {}", strCurrentPath);

        return exchange.getSession().flatMap(session -> {

            Map<String, Object> mapSession = session.getAttributes();
            LOGGER.info("==== mapSession ==== {}", mapSession);

            // 退出登录请求
            boolean bIsLogout = "/logout".equals(strCurrentPath);
            // 退出登录时清理 session
            if (bIsLogout) {
                session.getAttributes().clear();
            }

            // 判断是不是带登录信息的管理后台请求
            boolean bIsCurrentSystem =
                    (bIsLogout || "/index".equals(strCurrentPath) || strCurrentPath.startsWith("/system/"))
                    && CollectionUtils.isEmpty(mapSession);
            // 不带登录信息的管理后台请求重定向到登录页
            if (bIsCurrentSystem ) {

                URI uri = serverRequest.getURI();
                LOGGER.info("current uri ==== {}", uri);

                // 拼接登陆页面路径
                String strLoginUrl = uri.getScheme() + "://" + uri.getAuthority() + "/login";
                LOGGER.info("new url ==== {}", strLoginUrl);

                /*
                 * 重定向到登录页
                 * 参考 {@link org.springframework.cloud.gateway.filter.factory.RedirectToGatewayFilterFactory}
                 * 状态码必须是 3xx 才会重定向
                 */
                ServerHttpResponse response = exchange.getResponse();
                response.setStatusCode(HttpStatus.TEMPORARY_REDIRECT);
                response.getHeaders().set(HttpHeaders.LOCATION, strLoginUrl);
                return exchange.getResponse().setComplete();
            }

            // 非本系统请求及本系统静态资源直接放行
            return chain.filter(exchange);
        });


    }

}
